﻿// Copyright 2013 Ronald Schlenker, www.technewlogic.de.
// 
// This file is part of Byond.
// 
// Byond is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
// 
// Byond is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Byond.  If not, see <http://www.gnu.org/licenses/>.
using System;
using Byond.HostObjects;
using Utils.Documentation;

namespace Byond.Builtin
{
	[Doc(Summary = "")]
	public class Sampler
	{
		private readonly SampleBuffer _buffer;

		internal Sampler(SampleBuffer buffer)
		{
			_buffer = buffer;
			Speed = 1;
		}

		[Doc]
		public double O1 { get; private set; }
		[Doc]
		public double O2 { get; private set; }

		[Doc(Summary = "TODO: Was passiert, wenn das Ding am Ende ist?")]
		public double Position { get; set; }
		[Doc]
		public double Speed { get; set; }

		private readonly CallbackController _endController = new CallbackController();
		[Doc]
		public void End(Action del)
		{
			_endController.Register(del);
		}

		[Doc(Summary = "TODO: Was passiert, wenn das Ding am Ende ist?")]
		public void Next()
		{
			Update();
			Position += Speed;
		}

		[Doc]
		public void Update()
		{
			if (_buffer.Length < 2)
				return;

			var internalBuffer = _buffer.InternalBuffer;
			var position = (int)Position;
			if (position < 0)
			{
				Position = internalBuffer.Buffer1.Length - 1;
				position = (int)Position;
			}
			if (position >= _buffer.Length)
			{
				Position = 0;
				position = 0;

				if (_buffer.Length > 0)
					_endController.Raise();
			}

			O1 = internalBuffer.Buffer1[position];
			O2 = internalBuffer.Buffer2[position];
		}
	}
}
